﻿using System;
using System.Collections;
using System.Reflection;
using log4net;
using log4net.Config;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.ServiceModel;
using System.ComponentModel;
using System.ServiceModel.Security;
using System.Collections.Generic;
using System.ServiceModel.Description;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;


namespace HaiFang
{
    [Serializable]
    public class ProxyDocumentInfo
    {
        private static string PROCEDURE_QueryDocumentFolder = "QueryDocumentFolder";
        private static string PROCEDURE_QueryDocumentFolderID = "QueryDocumentFolderID";
        private static string PROCEDURE_QueryDocumentInfo = "QueryDocumentInfo";
        private static string PROCEDURE_QueryDocumentFilePath = "QueryDocumentFilePath";
        private static string PROCEDURE_InsertDocumentFolder = "InsertDocumentFolder";
        private static string PROCEDURE_InsertDocumentInfo = "InsertDocumentInfo";
        private static string PROCEDURE_DeleteDocumentFolder = "DeleteDocumentFolder";


        //@CurrUserID			int = null,					--管理员编号
        //@ProjectId			varchar(40)
        public static IList<DocumentFolder> QueryDocumentFolder(int CurrUserID, int ProjectID)
        {
            IList<DocumentFolder> list = new List<DocumentFolder>();
            try
            {
                using (SqlHelper helper = new SqlHelper())
                {
                    #region 构造参数
                    string comandText = PROCEDURE_QueryDocumentFolder;
                    List<SqlParameter> Parameters = new List<SqlParameter>();
                    Parameters.Add((new SqlParameter("@CurrUserID", CurrUserID)));
                    Parameters.Add(new SqlParameter("@ProjectID", ProjectID));
                    #endregion

                    #region 获取执行结果
                    DataTable dt = helper.ExecuteDataTable(comandText, CommandType.StoredProcedure, Parameters);
                    list = helper.GetObjects<DocumentFolder>(dt);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
            return list;
        }

        //@CurrUserID			int = null,					--管理员编号
        //@ProjectId			varchar(40),
        //@FilePath			varchar(512),				--带文件名的路径
        //@FolderID			int	output				
        public static void QueryDocumentFolderID(int CurrUserID, int ProjectID, string FilePath, out int FolderID)
        {
            FolderID = 0;
            try
            {
                using (SqlHelper helper = new SqlHelper())
                {
                    #region 构造参数
                    string comandText = PROCEDURE_QueryDocumentFolderID;
                    List<SqlParameter> Parameters = new List<SqlParameter>();
                    Parameters.Add((new SqlParameter("@CurrUserID", CurrUserID)));
                    Parameters.Add(new SqlParameter("@ProjectId", ProjectID));
                    Parameters.Add(new SqlParameter("@FilePath", FilePath));
                    Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@FolderID",
                        SqlDbType = SqlDbType.Int,
                        Direction = ParameterDirection.Output,
                        Value = FolderID
                    });
                    #endregion

                    #region 获取执行结果
                    helper.Execute(comandText, CommandType.StoredProcedure, Parameters);
                    #endregion

                    #region 获取output值
                    foreach (SqlParameter sp in Parameters)
                    {
                        if (sp.ParameterName == "@FolderID")
                        {
                            FolderID = helper.GetInt(sp.Value);
                            break;
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
        }

        //@CurrUserID			int = null,					--管理员编号
        //@ProjectId			varchar(40),
        //@FilePath			varchar(512),				--带文件名的路径
        //@AutoID				int	output							
        public static void QueryDocumentFilePath(int CurrUserID, int ProjectID, string FilePath, out int AutoID)
        {
            AutoID = 0;
            try
            {
                using (SqlHelper helper = new SqlHelper())
                {
                    #region 构造参数
                    string comandText = PROCEDURE_QueryDocumentFilePath;
                    List<SqlParameter> Parameters = new List<SqlParameter>();
                    Parameters.Add((new SqlParameter("@CurrUserID", CurrUserID)));
                    Parameters.Add(new SqlParameter("@ProjectId", ProjectID));
                    Parameters.Add(new SqlParameter("@FilePath", FilePath));
                    Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@AutoID",
                        SqlDbType = SqlDbType.Int,
                        Direction = ParameterDirection.Output,
                        Value = AutoID
                    });
                    #endregion

                    #region 获取执行结果
                    helper.Execute(comandText, CommandType.StoredProcedure, Parameters);
                    #endregion

                    #region 获取output值
                    foreach (SqlParameter sp in Parameters)
                    {
                        if (sp.ParameterName == "@AutoID")
                        {
                            AutoID = helper.GetInt(sp.Value);
                            break;
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
        }

        //@CurrUserID			int = null,					--管理员编号
        //@ProjectId			varchar(40),
        //@FolderID			bigint,
        //@SubFolder			tinyint=2,					--1:包含子文件夹   2：不包含子文件夹
        //@QueryStr			varchar(1000),				--关键词以空格进行分割
        //@QueryFlag			tinyint=1,					--1：like 
        //@AutoID				bigint=0					--查询所有时传0，否则传编号值	
        public static IList<DocumentInfo> QueryDocumentInfo(int CurrUserID, int ProjectId, int FolderID,int SubFolder,string QueryStr, int QueryFlag, int AutoID)
        {
            IList<DocumentInfo> list = new List<DocumentInfo>();
            try
            {
                using (SqlHelper helper = new SqlHelper())
                {
                    #region 构造参数
                    string comandText = PROCEDURE_QueryDocumentInfo;
                    List<SqlParameter> Parameters = new List<SqlParameter>();
                    Parameters.Add((new SqlParameter("@CurrUserID", CurrUserID)));
                    Parameters.Add(new SqlParameter("@ProjectId", ProjectId));
                    Parameters.Add(new SqlParameter("@FolderID", FolderID));
                    Parameters.Add(new SqlParameter("@SubFolder", SubFolder));
                    Parameters.Add(new SqlParameter("@QueryStr", QueryStr));
                    Parameters.Add(new SqlParameter("@QueryFlag", QueryFlag));
                    Parameters.Add(new SqlParameter("@AutoID", AutoID));
                    #endregion

                    #region 获取执行结果
                    DataTable dt = helper.ExecuteDataTable(comandText, CommandType.StoredProcedure, Parameters);
                    list = helper.GetObjects<DocumentInfo>(dt);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
            return list;
        }
        
        //@CurrUserID			int = null,					--管理员编号
        //@ProjectId			varchar(40),
        //@FilePath			varchar(512)				--带文件名的路径	
        //@FolderID			int	output	
        public static void InsertDocumentFolder(int CurrUserID, string ProjectId, string FilePath, out int FolderID)
        {
            FolderID = 0;
            try
            {
                using (SqlHelper helper = new SqlHelper())
                {
                    #region 构造参数
                    string comandText = PROCEDURE_InsertDocumentFolder;
                    List<SqlParameter> Parameters = new List<SqlParameter>();
                    Parameters.Add((new SqlParameter("@CurrUserID", CurrUserID)));
                    Parameters.Add(new SqlParameter("@ProjectId", ProjectId));
                    Parameters.Add(new SqlParameter("@FilePath", FilePath));
                    Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@FolderID",
                        SqlDbType = SqlDbType.Int,
                        Direction = ParameterDirection.Output,
                        Value = FolderID
                    });
                    #endregion

                    #region 获取执行结果
                    helper.Execute(comandText, CommandType.StoredProcedure, Parameters);
                    #endregion

                    #region 获取output值
                    foreach (SqlParameter sp in Parameters)
                    {
                        if (sp.ParameterName == "@FolderID")
                        {
                            FolderID = helper.GetInt(sp.Value);
                            break;
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
        }

        //@CurrUserID			int = null,					--管理员编号
        //@ProjectId			varchar(40),
        //@UseFlag			tinyint,					--1:insert   3:delete
        //@AutoID				bigint=0,					--@UseFlag为1时传0，其它操作传编号值
        //@FolderID			bigint,
        //@FilePath			varchar(512),				--带路径的文件名
        //@Description		varchar(128),
        //@ErrorMSG			int	output					--100：文档存在 200:错误  0：正确；其他：错误	
        public static void InsertDocumentInfo(int CurrUserID, string ProjectId, int UseFlag, int AutoID, int FolderID, string FilePath, string Description, out int ErrorMSG)
        {
            ErrorMSG = -1;
            try
            {
                using (SqlHelper helper = new SqlHelper())
                {
                    #region 构造参数
                    string comandText = PROCEDURE_InsertDocumentInfo;
                    List<SqlParameter> Parameters = new List<SqlParameter>();
                    Parameters.Add((new SqlParameter("@CurrUserID", CurrUserID)));
                    Parameters.Add(new SqlParameter("@ProjectId", ProjectId));
                    Parameters.Add(new SqlParameter("@UseFlag", UseFlag));
                    Parameters.Add(new SqlParameter("@AutoID", AutoID));
                    Parameters.Add(new SqlParameter("@FolderID", FolderID));
                    Parameters.Add(new SqlParameter("@FilePath", FilePath));
                    Parameters.Add(new SqlParameter("@Description", Description));
                    Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@ErrorMSG",
                        SqlDbType = SqlDbType.Int,
                        Direction = ParameterDirection.Output,
                        Value = ErrorMSG
                    });
                    #endregion

                    #region 获取执行结果
                    helper.Execute(comandText, CommandType.StoredProcedure, Parameters);
                    #endregion

                    #region 获取output值
                    foreach (SqlParameter sp in Parameters)
                    {
                        if (sp.ParameterName == "@ErrorMSG")
                        {
                            ErrorMSG = helper.GetInt(sp.Value);
                            break;
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
        }
        
        //@CurrUserID			int = null,					--管理员编号
        //@ProjectId			varchar(40),
        //@FolderID			int
        public static void DeleteDocumentFolder(int CurrUserID, string ProjectId, int FolderID)
        {
            try
            {
                using (SqlHelper helper = new SqlHelper())
                {
                    #region 构造参数
                    string comandText = PROCEDURE_DeleteDocumentFolder;
                    List<SqlParameter> Parameters = new List<SqlParameter>();
                    Parameters.Add((new SqlParameter("@CurrUserID", CurrUserID)));
                    Parameters.Add(new SqlParameter("@ProjectId", ProjectId));
                    Parameters.Add(new SqlParameter("@FolderID", FolderID));
                    #endregion

                    #region 获取执行结果
                    helper.Execute(comandText, CommandType.StoredProcedure, Parameters);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
        }

        /// <summary>
        /// 获取项目所在盘符
        /// </summary>
        /// <param name="CurrUserID"></param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        public static string GetProjectDisk(int CurrUserID, int ProjectId)
        {
            string ProjectDisk = string.Empty;
            IList<ProjectInfoBase> pis = ProxyProjectInfo.QueryProjectInfoSingle(CurrUserID, ProjectId);
            if (pis != null && pis.Count > 0)
            {
                ProjectInfoBase pi = pis[0];
                if (pi != null)
                {
                    //项目所在磁盘
                    ProjectDisk = pi.ProjectDisk;
                    /*if (ProjectDisk.IndexOf(":") < 0)
                    {
                        ProjectDisk = string.Format("{0}:\\", ProjectDisk);
                    }*/
                    if (!ProjectDisk.EndsWith("\\"))
                    {
                        ProjectDisk = string.Format("{0}\\", ProjectDisk);
                    }
                }
            }
            return ProjectDisk;
        }

        /// <summary>
        /// 同步文件夹和文档到数据库
        /// </summary>
        public static void SynchronismDocument(int CurrUserID, int ProjectId)
        {
            //项目所在磁盘
            string ProjectDisk = GetProjectDisk(CurrUserID, ProjectId);
            if (!String.IsNullOrEmpty(ProjectDisk))
            {
                //标准格式X:\
                Synchronism(CurrUserID, ProjectId, ProjectDisk, ProjectDisk);
            }
        }

        /// <summary>
        /// 递归同步
        /// </summary>
        /// <param name="CurrUserID"></param>
        /// <param name="ProjectId"></param>
        /// <param name="ProjectDisk"></param>
        /// <param name="FullPath"></param>
        private static void Synchronism(int CurrUserID, int ProjectId,string ProjectDisk,string FullPath)
        {
            DirectoryInfo theFolder = new DirectoryInfo(FullPath);
            //处理文件夹
            DirectoryInfo[] dirInfo = theFolder.GetDirectories();
            if (dirInfo != null && dirInfo.Length > 0)
            {
                foreach (DirectoryInfo di in dirInfo)
                {
                    Synchronism(CurrUserID, ProjectId,ProjectDisk,di.FullName);
                }
            }

            //添加文件夹
            int FolderID = 0;
            if (FullPath.Length > ProjectDisk.Length)
            {
                //截断项目盘
                string FolderPath = FullPath.Substring(ProjectDisk.Length-1);
                if (!FolderPath.EndsWith("\\"))
                {
                    FolderPath = string.Format("{0}\\", FolderPath);
                }
                InsertDocumentFolder(CurrUserID, ProjectId.ToString(), FolderPath,out FolderID);
            }

            //处理文件
            if (FolderID > 0)
            {
                FileInfo[] fileInfo = theFolder.GetFiles();
                if (fileInfo != null && fileInfo.Length > 0)
                {
                    //文件存在
                    foreach (FileInfo NextFile in fileInfo)
                    {
                        //去掉Thumbs.db文件
                        if (NextFile.Extension.ToLower() == ".db")
                        {
                            continue;
                        }
                        //添加文档
                        int ErrorMSG = -1;
                        string relativepath = NextFile.FullName.Replace(ProjectDisk, "");
                        if (!String.IsNullOrEmpty(relativepath) && relativepath.StartsWith("\\"))
                        {
                            relativepath = relativepath.Substring(1);
                        }
                        InsertDocumentInfo(CurrUserID, ProjectId.ToString(), 1, 0, FolderID, relativepath, string.Empty, out ErrorMSG);
                        //只记录日志
                        if (ErrorMSG != 0)
                        {
                            LogHelper.Writelog(LogType.LogType_Error, string.Format("InsertDocumentInfo error!{0}", ErrorMSG), null);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 上传文档信息
        /// </summary>
        /// <param name="CurrUserID"></param>
        /// <param name="ProjectId"></param>
        /// <param name="FullPath"></param>
        public static void UploadDocumentInfo(int CurrUserID, int ProjectId, string FullPath)
        {
            //项目所在磁盘
            string ProjectDisk = GetProjectDisk(CurrUserID, ProjectId);
            if (!String.IsNullOrEmpty(ProjectDisk))
            {
                //添加文件夹
                int FolderID = 0;
                if (FullPath.Length > ProjectDisk.Length)
                {
                    //截断项目盘
                    string FolderPath = FullPath.Substring(ProjectDisk.Length-1);
                    FolderPath = FolderPath.Remove(FolderPath.LastIndexOf("\\")+1);
                    InsertDocumentFolder(CurrUserID, ProjectId.ToString(), FolderPath, out FolderID);
                }

                //处理文件
                if (FolderID > 0)
                {
                    //添加文档
                    int ErrorMSG = -1;
                    string relativepath = FullPath.Replace(ProjectDisk,"");
                    if (!String.IsNullOrEmpty(relativepath)&&relativepath.StartsWith("\\"))
                    {
                        relativepath = relativepath.Substring(1);
                    }
                    InsertDocumentInfo(CurrUserID, ProjectId.ToString(), 1, 0, FolderID, relativepath, string.Empty, out ErrorMSG);
                    //只记录日志
                    if (ErrorMSG != 0)
                    {
                        LogHelper.Writelog(LogType.LogType_Error, string.Format("InsertDocumentInfo error!{0}", ErrorMSG), null);
                    }
                }
            }
        }

        /// <summary>
        /// 获取文档类型
        /// </summary>
        /// <param name="fileType"></param>
        /// <returns></returns>
        public static int GetDocumentFileType(string fileType)
        {
            int intFileType = 6;
            switch (fileType.ToLower().Replace(".", ""))
            {
                case "docx":
                    intFileType = 3;
                    break;
                case "doc":
                    intFileType = 3;
                    break;
                case "xls":
                    intFileType = 2;
                    break;
                case "xlsx":
                    intFileType = 2;
                    break;
                case "pdf":
                    intFileType = 4;
                    break;
                //case"txt":
                //    intFileType = 5;
                //    break;
                case "bmp":
                case "jpg":
                case "gif":
                case "png":
                case "tif":
                    intFileType = 5;
                    break;
                case "db":
                    //去掉Thumbs.db文件
                    intFileType = 7;
                    break;
                default:
                    intFileType = 6;
                    break;
            }
            return intFileType;
        }
    }

    [Serializable]
    public class DocumentFolder
    {
        public int AutoID { get; set; }
        public string GUID { get; set; }
        public int PrevFolderID { get; set; }
        public int FolderLevel { get; set; }
        public string FolderName { get; set; }
        public DateTime CreateTime { get; set; }
        public string Description { get; set; }
        public int DeleteFlag { get; set; }
    }

    [Serializable]
    public class DocumentInfo
    {
        public int AutoID { get; set; }
        public string GUID { get; set; }
        public int FolderID { get; set; }
        public string FileName { get; set; }
        public string FileExt { get; set; }
        public string FilePath { get; set; }
        public int OCRFlag { get; set; }
        public DateTime CreateTime { get; set; }
        public string Description { get; set; }
        public int DeleteFlag { get; set; }
    }
}